const express = require('express')
const router = express.Router()
const CurrentProject = require('../models/CurrentProject')
const { markFileAsReferenced, unmarkFileReference } = require('../middlewares/fileReference')
const authMiddleware = require('../middlewares/auth')

// 创建当前项目记录
router.post('/addCurrentProject', authMiddleware(), async (req, res) => {
  try {
    const {
      startDate,
      expectedEndDate,
      actualEndDate,
      fileId,
      projectName,
      projectType,
      priority,
      description,
      teamMembers,
      budget,
      progress,
      clientName,
      projectManager,
      status
    } = req.body

    // 验证日期格式
    if (!/^\d{4}-\d{2}-\d{2}$/.test(startDate)) {
      return res.status(400).json({ message: '开始日期格式应为YYYY-MM-DD' })
    }
    if (!/^\d{4}-\d{2}-\d{2}$/.test(expectedEndDate)) {
      return res.status(400).json({ message: '预期结束日期格式应为YYYY-MM-DD' })
    }
    if (actualEndDate && !/^\d{4}-\d{2}-\d{2}$/.test(actualEndDate)) {
      return res.status(400).json({ message: '实际结束日期格式应为YYYY-MM-DD' })
    }

    // 验证日期逻辑
    const start = new Date(startDate)
    const expectedEnd = new Date(expectedEndDate)
    if (start >= expectedEnd) {
      return res.status(400).json({ message: '预期结束日期必须晚于开始日期' })
    }

    if (actualEndDate) {
      const actualEnd = new Date(actualEndDate)
      if (actualEnd < start) {
        return res.status(400).json({ message: '实际结束日期不能早于开始日期' })
      }
    }

    const newCurrentProject = new CurrentProject({
      startDate,
      expectedEndDate,
      actualEndDate: actualEndDate || null,
      files: fileId,
      projectName,
      projectType,
      priority: priority || 2,
      description,
      teamMembers: teamMembers || [],
      budget: budget || 0,
      progress: progress || 0,
      clientName,
      projectManager,
      status: status || 1
    })

    const savedCurrentProject = await newCurrentProject.save()
    await markFileAsReferenced(fileId)

    res.status(201).json({
      data: savedCurrentProject,
      message: '创建成功'
    })
  } catch (err) {
    res.status(400).json({ message: err.message })
  }
})

// 查询当前项目记录（支持多条件筛选）
router.get('/queryCurrentProjects', async (req, res) => {
  try {
    const {
      year,
      currentProjectId,
      projectName,
      status,
      priority,
      projectType,
      clientName,
      projectManager,
      pageNum = 1,
      pageSize = 10
    } = req.query
    
    const filter = {}
    const options = {
      skip: (pageNum - 1) * pageSize,
      limit: parseInt(pageSize),
      sort: { createdAt: -1 }
    }

    if (currentProjectId) filter._id = currentProjectId
    if (year) filter.year = parseInt(year)
    if (status) filter.status = parseInt(status)
    if (priority) filter.priority = parseInt(priority)
    if (projectType) filter.projectType = { $regex: projectType, $options: 'i' }
    if (clientName) filter.clientName = { $regex: clientName, $options: 'i' }
    if (projectManager) filter.projectManager = { $regex: projectManager, $options: 'i' }
    if (projectName) {
      // 模糊查询
      filter.projectName = { $regex: projectName, $options: 'i' }
    }

    const [currentProjects, total] = await Promise.all([
      CurrentProject.find(filter)
        .populate('files')
        .skip(options.skip)
        .limit(options.limit)
        .sort(options.sort),
      CurrentProject.countDocuments(filter)
    ])

    res.json({
      data: currentProjects,
      pageNum: parseInt(pageNum),
      pageSize: parseInt(pageSize),
      totalPages: Math.ceil(total / options.limit),
      total,
      message: '查询成功'
    })
  } catch (err) {
    res.status(500).json({ message: err.message })
  }
})

// 获取当前项目详情
router.get('/getCurrentProjectDetail/:id', async (req, res) => {
  try {
    const currentProject = await CurrentProject.findById(req.params.id).populate('files')
    
    if (!currentProject) {
      return res.status(404).json({ message: '当前项目不存在' })
    }

    res.json({
      data: currentProject,
      message: '查询成功'
    })
  } catch (err) {
    res.status(500).json({ message: err.message })
  }
})

// 更新当前项目记录
router.post('/updateCurrentProject', authMiddleware(), async (req, res) => {
  try {
    const {
      fileId,
      currentProjectId,
      startDate,
      expectedEndDate,
      actualEndDate,
      projectName,
      projectType,
      priority,
      description,
      teamMembers,
      budget,
      progress,
      clientName,
      projectManager,
      status
    } = req.body
    
    const currentProject = await CurrentProject.findById(currentProjectId)

    if (!currentProject) {
      return res.status(404).json({ message: '当前项目不存在' })
    }

    // 验证日期格式和逻辑
    if (startDate && !/^\d{4}-\d{2}-\d{2}$/.test(startDate)) {
      return res.status(400).json({ message: '开始日期格式应为YYYY-MM-DD' })
    }
    if (expectedEndDate && !/^\d{4}-\d{2}-\d{2}$/.test(expectedEndDate)) {
      return res.status(400).json({ message: '预期结束日期格式应为YYYY-MM-DD' })
    }
    if (actualEndDate && !/^\d{4}-\d{2}-\d{2}$/.test(actualEndDate)) {
      return res.status(400).json({ message: '实际结束日期格式应为YYYY-MM-DD' })
    }

    // 处理文件更新
    if (fileId && fileId !== currentProject.files.toString()) {
      await unmarkFileReference(currentProject.files)
      await markFileAsReferenced(fileId)
      currentProject.files = fileId
    }

    // 更新年份（如果修改了开始日期）
    if (startDate) {
      currentProject.year = new Date(startDate).getUTCFullYear()
    }

    // 更新字段
    const updateFields = {
      startDate,
      expectedEndDate,
      actualEndDate,
      projectName,
      projectType,
      priority,
      description,
      teamMembers,
      budget,
      progress,
      clientName,
      projectManager,
      status
    }

    // 只更新提供的字段
    Object.keys(updateFields).forEach(key => {
      if (updateFields[key] !== undefined) {
        currentProject[key] = updateFields[key]
      }
    })

    const updatedCurrentProject = await currentProject.save()

    res.json({
      data: updatedCurrentProject,
      message: '更新成功'
    })
  } catch (err) {
    res.status(400).json({ message: err.message })
  }
})

// 删除当前项目记录
router.post('/deleteCurrentProject', authMiddleware(), async (req, res) => {
  try {
    const { currentProjectId } = req.body
    
    if (!currentProjectId) {
      return res.status(400).json({ message: '项目ID不能为空' })
    }

    const currentProject = await CurrentProject.findByIdAndDelete(currentProjectId)
    
    if (!currentProject) {
      return res.status(404).json({ message: '当前项目不存在' })
    }

    await unmarkFileReference(currentProject.files)

    res.json({ message: '删除成功' })
  } catch (err) {
    res.status(500).json({ message: err.message })
  }
})

// 批量删除当前项目记录
router.post('/batchDeleteCurrentProjects', authMiddleware(), async (req, res) => {
  try {
    const { currentProjectIds } = req.body
    
    if (!currentProjectIds || !Array.isArray(currentProjectIds) || currentProjectIds.length === 0) {
      return res.status(400).json({ message: '项目ID列表不能为空' })
    }

    const currentProjects = await CurrentProject.find({ _id: { $in: currentProjectIds } })
    
    if (currentProjects.length === 0) {
      return res.status(404).json({ message: '未找到要删除的项目' })
    }

    // 取消文件引用
    for (const project of currentProjects) {
      await unmarkFileReference(project.files)
    }

    const result = await CurrentProject.deleteMany({ _id: { $in: currentProjectIds } })

    res.json({ 
      message: `成功删除${result.deletedCount}个项目`,
      deletedCount: result.deletedCount
    })
  } catch (err) {
    res.status(500).json({ message: err.message })
  }
})

// 更新项目进度
router.post('/updateProgress', authMiddleware(), async (req, res) => {
  try {
    const { currentProjectId, progress } = req.body
    
    if (!currentProjectId) {
      return res.status(400).json({ message: '项目ID不能为空' })
    }
    
    if (progress === undefined || progress < 0 || progress > 100) {
      return res.status(400).json({ message: '进度值必须在0-100之间' })
    }

    const currentProject = await CurrentProject.findById(currentProjectId)
    
    if (!currentProject) {
      return res.status(404).json({ message: '当前项目不存在' })
    }

    currentProject.progress = progress
    
    // 如果进度达到100%，自动设置状态为已完成
    if (progress === 100 && currentProject.status === 1) {
      currentProject.status = 2
      if (!currentProject.actualEndDate) {
        currentProject.actualEndDate = new Date()
      }
    }

    const updatedCurrentProject = await currentProject.save()

    res.json({
      data: updatedCurrentProject,
      message: '进度更新成功'
    })
  } catch (err) {
    res.status(400).json({ message: err.message })
  }
})

// 获取项目统计信息
router.get('/getStatistics', async (req, res) => {
  try {
    const { year } = req.query
    const filter = year ? { year: parseInt(year) } : {}

    const [total, inProgress, completed, paused, cancelled, highPriority] = await Promise.all([
      CurrentProject.countDocuments(filter),
      CurrentProject.countDocuments({ ...filter, status: 1 }),
      CurrentProject.countDocuments({ ...filter, status: 2 }),
      CurrentProject.countDocuments({ ...filter, status: 3 }),
      CurrentProject.countDocuments({ ...filter, status: 4 }),
      CurrentProject.countDocuments({ ...filter, priority: { $gte: 3 } })
    ])

    const avgProgress = await CurrentProject.aggregate([
      { $match: { ...filter, status: 1 } },
      { $group: { _id: null, avgProgress: { $avg: '$progress' } } }
    ])

    res.json({
      data: {
        total,
        inProgress,
        completed,
        paused,
        cancelled,
        highPriority,
        averageProgress: avgProgress.length > 0 ? Math.round(avgProgress[0].avgProgress) : 0
      },
      message: '统计信息获取成功'
    })
  } catch (err) {
    res.status(500).json({ message: err.message })
  }
})

module.exports = router